<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账号" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
          <el-option
            v-for="dict in dict.type.min_user_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="回收商" prop="recoveryId">
        <el-select v-model="queryParams.recoveryId" placeholder="请选择回收商" clearable>
          <el-option v-for="item in businessList" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['api:user:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column label="编号" type="index" align="center" />
      <el-table-column label="账号" align="center" prop="username" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="类型" align="center" prop="type">
        <template v-slot="scope">
          <dict-tag :options="dict.type.min_user_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="回收商/公司" align="center" prop="recoveryId">
        <template v-slot="scope">
          <el-tag v-if="scope.row.type < 2" type="primary">
            {{formatBusiness(scope.row.recoveryId)}}
          </el-tag>
          <el-tag v-if="scope.row.type >= 2" type="success">
            {{formatCompany(scope.row.companyId)}}
          </el-tag>
          <div style="height: 10px"></div>
          <el-tag type="warning" v-if="scope.row.type > 2">
            {{formatStore(scope.row.storeId)}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" align="center" prop="loginTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.loginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['api:user:edit']"
            v-if="scope.row.type === 0 || scope.row.type === 2"
          >修改</el-button>
<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['api:user:remove']"
            v-if="scope.row.type === 0 || scope.row.type === 2"
          >删除</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-finance"
            @click="handleWallet(scope.row.id)"
            v-if="scope.row.type === 0 || scope.row.type === 2"
          >钱包</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号" :disabled="form.id" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" :maxlength="8" :minlength="2" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" :disabled="form.id">
            <el-option
              v-for="dict in dict.type.min_user_type"
              v-if="dict.value === '0' || dict.value === '2'"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="回收商" prop="recoveryId" v-if="form.type === 0">
          <el-select v-model="form.recoveryId" placeholder="请选择回收商" filterable @change="businessChange" :disabled="form.id">
            <el-option v-for="item in businessList" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="公司" prop="companyId" v-if="form.type === 2">
          <el-select v-model="form.companyId" placeholder="请选择公司" filterable @change="companyChange" :disabled="form.id">
            <el-option v-for="item in companyList" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 钱包列表 -->
    <el-drawer
      title="钱包信息"
      :visible.sync="walletOpen"
      direction="rtl"
      size="40%"
      :before-close="handleClose"
    >
      <Wallet :open="walletOpen" :user-id="walletUserId" />
    </el-drawer>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser } from "@/api/comment/user";
import {listBusiness} from "@/api/comment/business"
import {listCompany} from "@/api/comment/company"

import Wallet from "@/views/comment/user/wallet.vue";
export default {
  name: "User",
  dicts: ['min_user_type'],
  components: {Wallet},
  data() {
    return {
      //用户id
      walletUserId: null,
      //钱包开关
      walletOpen: false,
      //门店id
      storeList: [],
      //回收商列表
      businessList: [],
      //门店列表
      companyList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户列表表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        phone: null,
        nickName: null,
        type: null,
        recoveryId: null,
        companyId: null,
        storeId: null,
        loginTime: null,
        expireTime: null,
        sysUserId: null,
        createId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "账号不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getBusinessList();
    this.getCompanyList();
    this.getStoreList();
  },
  methods: {
    handleWallet(userId) {
      this.walletUserId = userId;
      this.walletOpen = true;
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    formatCompany(id) {
      let str = "";
      for (let i = 0; i < this.companyList.length; i++) {
        if(id === this.companyList[i].id) {
          str = this.companyList[i].name;
          break
        }
      }
      return str;
    },
    formatStore(id) {
      let str = "";
      for (let i = 0; i < this.storeList.length; i++) {
        if(id === this.storeList[i].id) {
          str = this.storeList[i].name;
          break
        }
      }
      return str;
    },
    formatBusiness(id) {
      for(let i = 0; i < this.businessList.length; i++) {
        if(id === this.businessList[i].id) {
          return this.businessList[i].name;
        }
      }
      return "";
    },
    /*获取回收商系统用户id*/
    businessChange() {
      for(let i = 0; i < this.businessList.length; i++) {
        if(this.form.recoveryId === this.businessList[i].id) {
          this.form.sysUserId = this.businessList[i].userId;
          return
        }
      }
    },
    /*获取公司系统用户id*/
    companyChange() {
      this.companyList.forEach(it => {
        if(it.id === this.form.companyId) {
          this.form.sysUserId = it.userId
        }
      })
    },
    //获取门店列表
    getStoreList() {
      const query = {
        type: 2
      }
      listCompany(query).then(res => {
        this.storeList = res.data;
      })
    },
    /*获取公司列表*/
    getCompanyList() {
      const query = {
        status: 2,
        type: 1,
        parentId: 0
      }
      listCompany(query).then(res => {
        this.companyList = res.data;
      })
    },
    /*获取回收商列表*/
    getBusinessList() {
      const query = {
        status: 2
      }
      listBusiness(query).then(res => {
        this.businessList = res.rows;
      })
    },
    /** 查询用户列表列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        username: null,
        password: null,
        phone: null,
        nickName: null,
        type: null,
        recoveryId: null,
        companyId: null,
        storeId: null,
        sysUserId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户列表";
      this.getBusinessList();
      this.getCompanyList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getBusinessList();
      this.getCompanyList();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.loginTime = undefined;
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户列表编号为"' + ids + '"的数据项？').then(function() {
        return delUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('api/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
